//
//  ForumViewController.m
//  parent
//
//  Created by yanzhen on 15/7/25.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "ForumViewController.h"
#import "CellStyleClassCircle.h"
#import "MJRefresh.h"
#import "NetWorkManager.h"
#import "BDKNotifyHUD.h"
#import "UserDao.h"
#import "PopUIManager.h"
#import "JsonUtil.h"
#import "UIImageView+WebCache.h"
#import "SMViewController.h"
#import "PostViewController.h"
#import "DetailNewViewController.h"
#import "JoinClassViewController.h"
#import "CityViewController.h"
#import "AFAppClient.h"
#import "ForumViewCell.h"
#import "HomeItemViewCell.h"
#import "KxMenu.h"
#import "Config.h"
#import "UMSocial.h"
#import "MyloginViewController.h"
#import "ChatViewController.h"

@interface ForumViewController ()<MWPhotoBrowserDelegate,UITableViewDataSource,UITableViewDelegate>
@property NSArray *data;
@property (weak, nonatomic) IBOutlet UIImageView *iconImg;
@property (weak, nonatomic) IBOutlet UILabel *topicNum;
@property (weak, nonatomic) IBOutlet UILabel *inNum;
@property (weak, nonatomic) IBOutlet UILabel *brief;

@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property NSMutableArray *topicData;
@property NSString *avatar_header;
@property BDKNotifyHUD *hud1;

@property MWPhotoBrowser *browser;

@property NSUInteger currentIndex;

@property (weak, nonatomic) IBOutlet UIView *headerView;

@end

@implementation ForumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self CustomBackButton];
    // Do any additional setup after loading the view from its nib.
    _data = @[@{@"type":@(1),@"image":@"文化养老2",@"title":@"文化养老",@"content":@"张扬你的个性 积极享受快乐"},
                   @{@"type":@(2),@"image":@"智慧生活2",@"title":@"智慧生活",@"content":@"依托云端服务 物联创新生活"},
                   @{@"type":@(3),@"image":@"健康养生2",@"title":@"健康养生",@"content":@"一手养生资讯 潮流健康生活"},
                   @{@"type":@(4),@"image":@"时尚汇2",@"title":@"时尚汇",@"content":@"时尚JOJO 坐镇聊穿衣"},
                   @{@"type":@(5),@"image":@"云律师2",@"title":@"云律师",@"content":@"世界律师平台 全球各地贴身保护"}
                   ];
    for (NSDictionary *dict in _data) {
        if([[dict objectForKey:@"type"]integerValue]==_type){
            _iconImg.image = [UIImage imageNamed:[dict objectForKey:@"image"]];
            self.navigationItem.title = [dict objectForKey:@"title"];
            _brief.text = [dict objectForKey:@"content"];
            break;
        }
    }
    _topicData = [[NSMutableArray alloc]init];
    [_tableview addHeaderWithTarget:self action:@selector(headerRereshing)];
    // [_tableview3 addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    // [_tableview headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    // [_tableview addFooterWithTarget:self action:@selector(footerRereshing)];
    [_tableview addFooterWithTarget:self action:@selector(footerRereshing)];
    //  [_tableview3 addFooterWithTarget:self action:@selector(footerRereshing)];
    
    //设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    //    _tableview.headerPullToRefreshText = @"下拉刷新";
    //    _tableview.headerReleaseToRefreshText = @"松开刷新";
    //    _tableview.headerRefreshingText = @"正在刷新...";
    //
    //    _tableview.footerPullToRefreshText = @"上拉加载";
    //    _tableview.footerReleaseToRefreshText = @"松开加载";
    //    _tableview.footerRefreshingText = @"正在加载...";
    
    _tableview.headerPullToRefreshText = @"下拉刷新";
    _tableview.headerReleaseToRefreshText = @"松开刷新";
    _tableview.headerRefreshingText = @"正在刷新...";
    
    _tableview.footerPullToRefreshText = @"上拉加载";
    _tableview.footerReleaseToRefreshText = @"松开加载";
    _tableview.footerRefreshingText = @"正在加载...";
    [_tableview headerBeginRefreshing];
//    [_headerView removeFromSuperview];
    _tableview.tableHeaderView = _headerView;
}

//================顶部刷新，获取最新动态=========================
//首次进入会自动执行一次获取最新动态
- (void)headerRereshing
{
    if ([NetWorkManager connectedToNetwork]) {
        [self getArticles:@"new" withBaseid:0];
    }else{
        //没有网络的情况下，加载本地缓存数据
        [_hud1 presentWithDuration:1.0f speed:0.5f inView:self.view completion:^{
            [_hud1 removeFromSuperview];
        }];
        
    }
}

//================底部刷新，获取更多班级圈=========================
- (void)footerRereshing
{
    if([NetWorkManager connectedToNetwork]) {
        NSDictionary *lastObject;
        [self getArticles:@"old" withBaseid:[[lastObject objectForKey:@"id"]integerValue]];
        
    }else{
        [_hud1 presentWithDuration:1.0f speed:0.5f inView:self.view completion:^{
            [_hud1 removeFromSuperview];
        }];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 7.01f;
}

-(void)getArticles:(NSString*)requestType withBaseid:(NSUInteger)baseid
{
    //NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    //NSString* utype = @"1";
    NSUInteger is_rec= 0;
    
    NSDictionary *temp_dict = [[NSDictionary alloc]initWithObjectsAndKeys:@(_type),@"posttype",requestType,@"dir",@(baseid), @"baseid",@(is_rec),@"is_rec", nil];
    
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,API_USER_GET_ARTICLES] withParameters:temp_dict success:^(NSDictionary *dict) {
        [popUIMgr removeWaitingUI];
        if ([requestType isEqualToString:@"new"]) {
            [self.tableview headerEndRefreshing];
        }else if ([requestType isEqualToString:@"old"]){
            [self.tableview footerEndRefreshing];
            
        }
        if ([[dict objectForKey:@"ret"] integerValue]== 1) {
            NSUInteger retCode = [[dict objectForKey:@"retCode"] integerValue];
            switch (retCode) {
                case 1:
                {
                    _avatar_header = [dict objectForKey:@"avatar_header"];
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        
                            [_topicData removeAllObjects];
                        
                    }
                    NSArray *posts = [dict objectForKey:@"posts"];
                    NSUInteger post_num = [[dict objectForKey:@"post_num"]integerValue];
                    NSUInteger total_num = [[dict objectForKey:@"total_num"]integerValue];
                    _topicNum.text = [NSString stringWithFormat:@"%ld",post_num];
                    _inNum.text = [NSString stringWithFormat:@"%ld",total_num];
                        for (NSDictionary *item in posts) {
                            [_topicData addObject:item];
                        }
                        [_tableview reloadData];
                    
                    break;
                }
                case 10020:
                {
                    [_hud1 setImage:[UIImage imageNamed:@"Checkmark"]];
                    [_hud1 setText:@"没有更多数据了"];
                    [_hud1 presentWithDuration:1.0 speed:.5 inView:self.view completion:^{
                        
                    }];
                    break;
                }
                    
                default:
                    break;
            }
            
        }else{
            [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
        }
    } failure:^(NSError *error) {
        [popUIMgr removeWaitingUI];
        if ([requestType isEqualToString:@"new"]) {
            
                [self.tableview headerEndRefreshing];
            
        }else if ([requestType isEqualToString:@"old"]){
            
                [self.tableview footerEndRefreshing];
            
        }
        [popUIMgr popAlertView:nil title:@"提示" message:@"网络连接出错" cancelButtonTitle:@"确定"];
    }];
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
        static NSString *CellIdentifier = @"CellStyleClassCircle";
        CellStyleClassCircle *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"CellStyleClassCircle" owner:self options:nil];
            cell = (CellStyleClassCircle *)[nibArr objectAtIndex:0];
            [cell setAccessoryType:UITableViewCellAccessoryNone];
        }
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        NSDictionary *article;
        article = [_topicData objectAtIndex:indexPath.row];
        
        
        NSString *avatar =[article objectForKey:@"author_avatar"];
        [cell.avatar sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",_avatar_header,avatar]] placeholderImage:[UIImage imageNamed:@"default_circle_icon"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
        }];
        cell.avatar.layer.cornerRadius = 20;
        cell.avatar.layer.masksToBounds = YES;
        
        NSString *title = [article objectForKey:@"title"];
        cell.title.text = title;
        
        NSString *post_time = [article objectForKey:@"post_time"];
        cell.time.text = post_time;
        
        NSString *relpynum = [article objectForKey:@"replynum"];
        cell.replyNum.text = [NSString stringWithFormat:@"%@",relpynum];
        
        NSString *transfernum = [article objectForKey:@"transfernum"];
        cell.transferNum.text = [NSString stringWithFormat:@"%@",transfernum];
        
        NSString *goodnum = [article objectForKey:@"goodnum"];
        cell.goodNum.text = [NSString stringWithFormat:@"%@",goodnum];
        
        NSString *author_name = [article objectForKey:@"content"];
        cell.author.text = author_name;
     */
    static NSString *CellIdentifier = @"HomeItemViewCell";
    HomeItemViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        @try{
            NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"HomeItemViewCell" owner:self options:nil];
            cell = (HomeItemViewCell *)[nibArr objectAtIndex:0];
        }
        @catch(NSException *exception) {
            NSLog(@"exception:%@", exception);
        }
        @finally {
            
        }
        //        cell = [[HomeItemViewCell alloc]init];
        [cell setAccessoryType:UITableViewCellAccessoryNone];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    NSDictionary *article;
    article = [_topicData objectAtIndex:indexPath.row];
    /*
    NSUInteger type = [[article objectForKey:@"type"]integerValue];
    for (NSDictionary *dict in _data) {
        if(type == [[dict objectForKey:@"type"]integerValue]){
            //cell.forumIcon.image = [UIImage imageNamed:[dict objectForKey:@"image"]];
            cell.forumTitle.text = [dict objectForKey:@"title"];
            cell.forumTitle.textColor = [dict objectForKey:@"color"];
            break;
        }
    }
     */
    [cell.forumTitle setHidden:YES];
    
    NSString *avatar =[article objectForKey:@"author_avatar"];
    [cell.avatar sd_setImageWithURL:[NSURL URLWithString:avatar] placeholderImage:[UIImage imageNamed:@"default_circle_icon"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
    }];
    cell.avatar.layer.cornerRadius = 16.5;
    cell.avatar.layer.masksToBounds = YES;
    
    cell.avatar.userInteractionEnabled = YES;
    cell.avatar.tag = indexPath.row;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chatView:)];
    [cell.avatar addGestureRecognizer:tap];
    
    NSString *author_name = [article objectForKey:@"author_name"];
    [cell.author setText:author_name];
    
    NSString *title = [article objectForKey:@"title"];
    cell.title.text = title;
    
    NSString *post_time = [article objectForKey:@"new_post_time"];
    cell.time.text = post_time;
    
    NSString *relpynum = [article objectForKey:@"replynum"];
    cell.replyNum.text = [NSString stringWithFormat:@"%@",relpynum];
    
    NSString *goodnum = [article objectForKey:@"goodnum"];
    cell.goodNum.text = [NSString stringWithFormat:@"%@",goodnum];
    
    NSString *city = [article objectForKey:@"author_city"];
    cell.city.text = city;
    
    NSString *sex =[NSString stringWithFormat:@"%@", [article objectForKey:@"author_sex"]];
    
    if([sex isEqualToString:@"1"]){
        cell.sexImg.image = [UIImage imageNamed:@"man"];
    }else{
        cell.sexImg.image = [UIImage imageNamed:@"woman"];
    }
    
    NSArray *pics = [article objectForKey:@"pics"];
    int imageTag = 100 * indexPath.row;
    if(pics&& [pics count]>0){
        cell.picViewHight.constant = 80 + (80+6)*(([pics count]-1)/3);
        NSArray *subviews = [cell.picsView subviews];
        for (UIView *v in subviews) {
            [v removeFromSuperview];
        }
        for (NSUInteger i=0; i<[pics count]; i++) {
            NSString *ul = [pics objectAtIndex:i];
            NSUInteger pic_width = 80;
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(i%3*(pic_width+6), ((i/3)*(pic_width+6)), pic_width, pic_width)];
            [image setContentMode:UIViewContentModeScaleAspectFill];
            image.clipsToBounds  = YES;
            image.userInteractionEnabled = YES;
            UITapGestureRecognizer *ges=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showImages:)];
            [image addGestureRecognizer:ges];
            image.tag = imageTag;
            imageTag++;

            [image sd_setImageWithURL:[NSURL URLWithString:ul] placeholderImage:nil];
            [cell.picsView addSubview:image];
        }
    }else{
        cell.picViewHight.constant = 0;
    }
    cell.popButton.tag = indexPath.row;
    
    cell.shareView.userInteractionEnabled = YES;
    UITapGestureRecognizer *gest = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickShare:)];
    [cell.shareView addGestureRecognizer:gest];
    
    cell.goodView.userInteractionEnabled = YES;
    UITapGestureRecognizer *gest1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(goods:)];
    [cell.goodView addGestureRecognizer:gest1];
    cell.goodView.tag =[[article objectForKey:@"id"]integerValue];
    
    return cell;
}

-(void)chatView:(UITapGestureRecognizer*)rec
{
    UIView *view = [rec view];
    NSUInteger tag = [view tag];
    NSDictionary *article = [_topicData objectAtIndex:tag];
    
    ChatViewController *chatVC = [[ChatViewController alloc] initWithChatter:[article objectForKey:@"author_id"] isGroup:NO];
    //            chatVC.title = [[UserProfileManager sharedInstance] getNickNameWithUsername:buddy.username];
    chatVC.title = [article objectForKey:@"author_name"];
    chatVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatVC animated:YES];
}

-(void)goods:(UITapGestureRecognizer*)sender
{
    if([[Config Instance]isCookie]){
        UIView *view = [sender view];
        NSUInteger tag = [view tag];
        if(tag>0){
            PopUIManager *popUIMgr = [PopUIManager getInstanse];
            [popUIMgr showWaitingUI:self.view];
            [[AFAppClient sharedManager]getWithURL:[NSString stringWithFormat:@"%@%@",SERVER_URL_NEW,kUserPostGood] withParameters:@{@"uid":@([[Config Instance]getUID]),@"pid":@(tag)} success:^(NSDictionary *responseObject) {
                [popUIMgr removeWaitingUI];
                [_tableview headerBeginRefreshing];
            } failure:^(NSError *error) {
                [popUIMgr removeWaitingUI];
            }];
        }else{
            
        }
        
    }else{
        
        MyloginViewController *login = [MyloginViewController shareController];
        
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
        
    }
}
-(void)clickShare:(id)sender
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55a73f3a67e58e7b700001c9"
                                      shareText:@"阿莱回家，国内最大的中老年人线上交流平台，www.zgyxyl.com"
                                     shareImage:[UIImage imageNamed:@"share_icon"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToWechatTimeline,UMShareToWechatSession,UMShareToQQ,UMShareToQzone,nil]
                                       delegate:self];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"%@",indexPath);
    //该方法响应列表中行的点击事件
    NSInteger row = indexPath.row;
    NSDictionary *dict= [_topicData objectAtIndex:row];
    
    NSUInteger pid = [[dict objectForKey:@"id"]integerValue ];
    DetailNewViewController *detail = [[DetailNewViewController alloc]init];
    detail.msgId = [NSString stringWithFormat:@"%ld",pid];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_topicData count];
}

//设置Cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return [self getHeightByIndex:indexPath.row];
    
}

-(NSUInteger)getHeightByIndex:(NSUInteger)index
{
    NSDictionary *article;
    article = [_topicData objectAtIndex:index];
    NSArray *pics = [article objectForKey:@"pics"];
    if(pics&& [pics count]>0){
        NSUInteger length = [pics count];
        return 134+80 + (80+6)*((length-1)/3) ;
    }else{
        return 134;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)showImages:(UITapGestureRecognizer *)tap{
    UIView *view = [tap view];
    NSUInteger index = view.tag/100;
    NSDictionary *article;
    
    _currentIndex = index;
    
    NSInteger i = view.tag % 100;
    
    // if(_browser == nil) {
    _browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    _browser.displayActionButton = NO;
    _browser.displayNavArrows = YES;
    _browser.enableGrid = NO;
    // }
    
    [_browser setCurrentPhotoIndex:i];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:_browser];
    nc.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:nc animated:YES completion:nil];
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser {
    NSDictionary *article = [_topicData objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    return pics.count;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index {
    NSDictionary *article = [_topicData objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    if (index < pics.count)
        return [MWPhoto photoWithURL:[NSURL URLWithString:[pics objectAtIndex:index]]];
    return nil;
}

- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser thumbPhotoAtIndex:(NSUInteger)index {
    NSDictionary *article = [_topicData objectAtIndex:_currentIndex];
    NSArray *pics = [article objectForKey:@"pics"];
    if (index < pics.count)
        return [MWPhoto photoWithURL:[NSURL URLWithString:[pics objectAtIndex:index]]];
    return nil;
}

- (IBAction)pubAction:(id)sender {
    if([[Config Instance]isCookie]){
        PostViewController *postView  = [[PostViewController alloc]init];
        postView.postType = [NSString stringWithFormat:@"%ld",_type];
        UINavigationController *post_nav = [[UINavigationController alloc]initWithRootViewController:postView];
        [self presentViewController:post_nav animated:YES completion:^{
            
        }];
    }else{
        MyloginViewController *login = [MyloginViewController shareController];
        UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:^{
            
        }];
    }
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
